package com.tsf.filter;

import com.tsf.common.exception.CommonErrorMessage;
import com.tsf.common.exception.CommonException;
import com.tsf.common.result.R;
import com.tsf.common.result.REnum;
import com.tsf.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


/**
 * Created by bpf on 2020/12/22.
 */
@Slf4j
public class HttpFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        byte[] resByte = null;
        RequestWrapper requestWrapper = null;
        long t1 = System.nanoTime();
        try {
            requestWrapper = new RequestWrapper((HttpServletRequest) request);
            ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
            String requestBody = "";
            if (RequestMethod.POST.toString().equals(requestWrapper.getMethod())) {
                requestBody = new String(requestWrapper.getRequestBody(), request.getCharacterEncoding());
            } else {
                requestBody = JsonUtils.toJson(requestWrapper.getParameterMap());
            }
            log.info("req[{}] -- url={} -- body={}", requestWrapper.getMethod(), requestWrapper.getRequestURL(), requestBody);
            chain.doFilter(requestWrapper, responseWrapper);
            resByte = responseWrapper.getResponseBody();
        } catch (Exception e) {
            //TODO 关掉生产端，直接进入服务降级，此处未能捕获此情况异常
            resByte= JsonUtils.toJson(R.error(new CommonErrorMessage(REnum.SERVICE_RESULT_ERROR, e.getMessage()))).getBytes(request.getCharacterEncoding());
        } finally {
            response.getOutputStream().write(resByte);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            long t2 = System.nanoTime();
            log.info("res[{}] -- url={}  -- body={}", String.format("%.1fms", (t2 - t1) / 1e6d), requestWrapper.getRequestURL(), new String(resByte, request.getCharacterEncoding()));
        }
    }


    /**
     * 获取头信息
     *
     * @param requestWrapper
     * @return
     */
    private StringBuffer getHeads(RequestWrapper requestWrapper) {
        Enumeration headerNames = requestWrapper.getHeaderNames();
        StringBuffer buffer = new StringBuffer();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            buffer.append(headerName + " : " + requestWrapper.getHeader(headerName) + "\n");
        }
        return buffer;
    }
}
